package com.redwine.app.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.redwine.app.APP;
import com.redwine.app.PublishedSourcesDetailActivity;
import com.redwine.app.R;
import com.redwine.app.adapter.PublishedSourcesAdapter;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.DownOptionsBean;
import com.redwine.app.net.responses.PublishCategoryResponse;
import com.redwine.app.net.responses.SendMsgEvent;
import com.redwine.app.net.responses.SupplyOfGoodsResponse;
import com.redwine.app.utils.NetUtil;
import com.redwine.app.view.CommonPopupListWindow;
import com.redwine.app.view.EmptyView;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.redwine.app.utils.Utils.showToast;

/**
 * 货源主页面
 * 作者：gassion on 17/8/20 01:36
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class PublishedSourcesFragment extends BaseFragment {

    private View rootView;
    @ViewInject(R.id.supply_of_goods_refresh_list_view)
    private PullToRefreshListView mListView;
    @ViewInject(R.id.layout_right_tv_title)
    private TextView headerRightTitle;
    @ViewInject(R.id.header_title)
    private TextView headerTitle;
    @ViewInject(R.id.supply_ll_all)
    private LinearLayout supplyLlAll;
    @ViewInject(R.id.supply_tv_category)
    private TextView supplyTvCategory;
    @ViewInject(R.id.supply_tv_goods_origin)
    private TextView supplyTvCountry;
    @ViewInject(R.id.supply_tv_goods_address)
    private TextView supplyTvCity;
    @ViewInject(R.id.supply_ll_category)
    private LinearLayout supplyLlCategory;
    @ViewInject(R.id.supply_ll_goods_origin)
    private LinearLayout supplyLlCountry;
    @ViewInject(R.id.supply_ll_goods_address)
    private LinearLayout supplyLlCity;
    @ViewInject(R.id.empty_view)
    private EmptyView emptyView;
    private int page = 1;//默认加载第一页
    private PublishedSourcesAdapter publishedSourcesAdapter;
    private List<DownOptionsBean> mListCategoryData = new ArrayList<>();
    private List<DownOptionsBean> mListCityData = new ArrayList<>();
    private List<DownOptionsBean> mListCountryData = new ArrayList<>();
    private String mCategoryId = "";
    private String mCountryId = "";
    private String mCityId = "";
    private boolean isLoadingAll;//是否加载全部

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (null != rootView) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (null != parent) {
                parent.removeView(rootView);
            }
        } else {
            rootView = inflater.inflate(R.layout.fragment_supply_of_goods, container, false);
            ViewUtils.inject(this, rootView);
            EventBus.getDefault().register(this);
            initView();
            requestPublishCategoryData();
        }
        return rootView;
    }

    private void initView() {
        headerRightTitle.setText(R.string.all);
        headerRightTitle.setVisibility(View.VISIBLE);
        headerRightTitle.setTextColor(getResources().getColor(R.color.white));
        headerTitle.setText(getString(R.string.goods));
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (isLoadingAll) {
                    requestPublishCategoryData();
                } else {
                    page = 1;
                    requestListData(false);
                }
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page += 1;
                requestListData(false);
            }
        });
        mListView.setOnActionMoveListener(new PullToRefreshBase.OnActionMove() {
            @Override
            public void onMove(boolean isMove) {
                setUpdateTime(mListView);
            }
        });
        mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        publishedSourcesAdapter = new PublishedSourcesAdapter(getActivity());
        mListView.setAdapter(publishedSourcesAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SupplyOfGoodsResponse.DataEntityX.DataEntity dataEntity = (SupplyOfGoodsResponse.DataEntityX.DataEntity) parent.getAdapter().getItem(position);
                Intent intent = new Intent(getActivity(), PublishedSourcesDetailActivity.class);
                intent.putExtra(PublishedSourcesDetailActivity.SHOP_NAME, dataEntity.getName());
                intent.putExtra(PublishedSourcesDetailActivity.SHOP_UID, dataEntity.getUid());
                intent.putExtra(PublishedSourcesDetailActivity.SHOP_ID, dataEntity.getId());
                startActivity(intent);
            }
        });
        mListView.setEmptyView(emptyView);
        emptyView.bind();
    }

    /**
     * 请求品类&产地&所在地
     */
    private void requestPublishCategoryData() {
        if (!NetUtil.checkNet(getActivity())) {
            isLoadingAll = true;
            showToast(R.string.generic_check);
            setErrorView(emptyView, mListView);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != mListView)
                        mListView.onRefreshComplete();

                }
            }, 500);
            return;
        }

        showWaiting();
        String url = NetworkConstants.PUBLISH_CATEGORY_URL;
        GsonRequest<PublishCategoryResponse> request = new GsonRequest<>(url, Request.Method.POST,
                PublishCategoryResponse.class, false, null, new Response.Listener<PublishCategoryResponse>() {
            @Override
            public void onResponse(PublishCategoryResponse response) {
                if (response.isSuccess()) {
                    PublishCategoryResponse.DataEntity dataEntity = response.getData();
                    mListCategoryData = dataEntity.getCategory();
                    mListCityData = dataEntity.getCity();
                    mListCountryData = dataEntity.getCountry();
                    requestListData(false);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    /**
     * 请求列表数据
     */
    private void requestListData(boolean isLoading) {
        if (!NetUtil.checkNet(getActivity())) {
            isLoadingAll = false;
            if (publishedSourcesAdapter.getData().isEmpty()) {
                setErrorView(emptyView, mListView);
            }
            showToast(R.string.generic_check);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != mListView)
                        mListView.onRefreshComplete();

                }
            }, 500);
            return;
        }

        if (isLoading)
            showWaiting();
        String url = NetworkConstants.SEARCH_WINE_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("category", mCategoryId);
        params.put("country", mCountryId);
        params.put("province", mCityId);
        params.put("size", "20");
        params.put("page", String.valueOf(page));
        GsonRequest<SupplyOfGoodsResponse> request = new GsonRequest<>(url, Request.Method.POST,
                SupplyOfGoodsResponse.class, false, params, new Response.Listener<SupplyOfGoodsResponse>() {
            @Override
            public void onResponse(SupplyOfGoodsResponse response) {
                dismissWaiting();
                if (null != mListView)
                    mListView.onRefreshComplete();
                if (response.isSuccess()) {
                    SupplyOfGoodsResponse.DataEntityX responseData = response.getData();
                    updateCommentView(responseData);
                } else {
                    setEmptyView(emptyView, mListView);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissWaiting();
                if (null != mListView)
                    mListView.onRefreshComplete();
                setEmptyView(emptyView, mListView);
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }

    private void updateCommentView(SupplyOfGoodsResponse.DataEntityX responseData) {
        if (null != responseData && null != responseData.getData() && responseData.getData().isEmpty())
            setEmptyView(emptyView, mListView);
        List<SupplyOfGoodsResponse.DataEntityX.DataEntity> responseDataData = responseData.getData();
        publishedSourcesAdapter.setData(page, responseDataData);
        if (responseData.getPage() != responseData.getAllpage()) {
            mListView.setMode(PullToRefreshBase.Mode.BOTH);
        } else {
            mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MainScreen");

    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MainScreen");
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onStart() {
        super.onStart();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    /**
     * 设置更新时间
     */
    protected void setUpdateTime(PullToRefreshListView mListView) {
        String label = DateUtils.formatDateTime(getActivity(),
                System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                        | DateUtils.FORMAT_SHOW_DATE
                        | DateUtils.FORMAT_ABBREV_ALL);
        mListView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
    }


    /**
     * 显示下拉选项
     *
     * @param textView
     */
    private void showDownOptions(final LinearLayout linearLayout, final TextView textView, final List<DownOptionsBean> stringList) {
        textView.setTextColor(getResources().getColor(R.color.white));
        if (linearLayout.equals(supplyLlCategory)) {
            linearLayout.setBackgroundResource(R.drawable.supply_left_shape_select);
        } else if (linearLayout.equals(supplyLlCountry)) {
            linearLayout.setBackgroundResource(R.drawable.supply_middle_shape_select);
        } else {
            linearLayout.setBackgroundResource(R.drawable.supply_right_shape_select);
        }
        CommonPopupListWindow popupListWindow = new CommonPopupListWindow(getActivity(), stringList);
        popupListWindow.setOnClickListener(new CommonPopupListWindow.OnClickListener() {
            @Override
            public void onClick(int position) {
                if (linearLayout.equals(supplyLlCategory)) {
                    mCategoryId = stringList.get(position).getId();
                } else if (linearLayout.equals(supplyLlCountry)) {
                    mCountryId = stringList.get(position).getId();
                } else {
                    mCityId = stringList.get(position).getId();
                }
                textView.setText(stringList.get(position).getName());
                requestListData(true);
            }
        });
        popupListWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                textView.setTextColor(getResources().getColor(R.color.dark_gray_3));
                linearLayout.setBackgroundColor(getResources().getColor(R.color.tranparnt));
            }
        });
        popupListWindow.showAsDropDown(supplyLlAll);
    }

    @OnClick({R.id.supply_ll_category, R.id.supply_ll_goods_origin, R.id.supply_ll_goods_address, R.id.layout_right_tv_title})
    public void mClick(View v) {

        switch (v.getId()) {

            case R.id.supply_ll_category:
                //品类
                showDownOptions(supplyLlCategory, supplyTvCategory, mListCategoryData);
                break;

            case R.id.supply_ll_goods_origin:
                //产地
                showDownOptions(supplyLlCountry, supplyTvCountry, mListCountryData);
                break;

            case R.id.supply_ll_goods_address:
                //所在地
                showDownOptions(supplyLlCity, supplyTvCity, mListCityData);
                break;

            case R.id.layout_right_tv_title:
                supplyTvCategory.setText(getString(R.string.category));
                supplyTvCountry.setText(getString(R.string.supply_goods_origin));
                supplyTvCity.setText(getString(R.string.supply_goods_address));
                mCategoryId = "";
                mCountryId = "";
                mCityId = "";
                requestListData(true);
                break;

        }
    }


    public void onEventMainThread(SendMsgEvent event) {
        if (event.getSendType() == SendMsgEvent.REFURBISH_PUBLISHDE_LIST) {
            requestListData(true);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }


    @Override
    protected void emptyOnclick() {
        emptyView.bind();
        if (isLoadingAll) {
            requestPublishCategoryData();
            return;
        }

        if (null != mListView) {
            mListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    mListView.setRefreshing();
                }
            }, 500);
        } else {
            requestListData(true);
        }
    }
}